<template>
  <div class="storage-bucket-container">
    <!-- 操作栏 -->
    <div class="operate-bar">
      <el-button type="primary" @click="openAddDialog">
        <el-icon>
          <Plus/>
        </el-icon>
        新增存储桶
      </el-button>
    </div>
    <!-- 表格 -->
    <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%; margin-top: 10px"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="id" label="ID" width="80" align="center"/>
      <el-table-column prop="bucketName" label="存储桶名称" align="center"/>
      <el-table-column prop="storageType" label="存储类型" align="center">
        <template #default="scope">
          <el-tag
              :type="scope.row.storageType === 'minio' ? 'primary' :
                   scope.row.storageType === 'oss' ? 'success' : 'info'"
          >
            {{
              scope.row.storageType === 'minio' ? 'MinIO' :
                  scope.row.storageType === 'oss' ? '阿里云OSS' : '本地存储'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="region" label="存储区域" align="center"/>
      <el-table-column prop="baseUrl" label="访问基础URL" align="center"/>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="openEditDialog(scope.row)"
          >
            <el-icon>
              <Edit/>
            </el-icon>
            编辑
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
          >
            <el-icon>
              <Delete/>
            </el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表单弹窗 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="formRef"
          :model="bucketForm"
          :rules="formRules"
          label-width="120px"
          style="margin-top: 20px"
      >
        <el-form-item label="存储桶名称" prop="bucketName">
          <el-input
              v-model="bucketForm.bucketName"
              placeholder="请输入存储桶名称"
              :disabled="dialogType === 'edit'"
          />
        </el-form-item>
        <el-form-item label="存储类型" prop="storageType">
          <el-select
              v-model="bucketForm.storageType"
              placeholder="请选择存储类型"
          >
            <el-option label="MinIO" value="minio"/>
            <el-option label="阿里云OSS" value="oss"/>
            <el-option label="本地存储" value="local"/>
          </el-select>
        </el-form-item>
        <el-form-item label="存储区域" prop="region">
          <el-input
              v-model="bucketForm.region"
              placeholder="请输入存储区域（如us-east-1）"
          />
        </el-form-item>
        <el-form-item label="访问密钥" prop="accessKey">
          <el-input
              v-model="bucketForm.accessKey"
              placeholder="请输入访问密钥"
          />
        </el-form-item>
        <el-form-item label="密钥" prop="secretKey">
          <el-input
              v-model="bucketForm.secretKey"
              placeholder="请输入密钥"
              show-password
          />
        </el-form-item>
        <el-form-item label="访问基础URL" prop="baseUrl">
          <el-input
              v-model="bucketForm.baseUrl"
              placeholder="请输入访问基础URL（如http://minio.example.com）"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
              v-model="bucketForm.status"
              active-value="1"
              inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="bucketForm.remark"
              placeholder="请输入备注信息"
              type="textarea"
              rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="dialogType === 'add' ? handleAdd() : handleUpdate()"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue'
import {Plus, Edit, Delete} from '@element-plus/icons-vue'
import type {ElForm, ElTable} from 'element-plus'
import type {StorageBucket} from "@/api/file/bucket/type"
import {reqCreateBucket, reqGetBucketList} from "@/api/file/bucket";
import {formatDate} from "@/util"; // 需安装date-fns：npm install date-fns


// 表格数据
const tableData = ref<StorageBucket[]>([])
// 选中项
const selectedRows = ref<StorageBucket[]>([])
// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const dialogTitle = ref('新增存储桶')
const formRef = ref<InstanceType<typeof ElForm>>()

// 表单数据
const bucketForm = reactive<StorageBucket>({
  bucketName: '',
  storageType: '',
  region: '',
  accessKey: '',
  secretKey: '',
  baseUrl: '',
  status: '1', // 默认启用
  remark: ''
})

// 表单验证规则
const formRules = reactive({
  bucketName: [
    {required: true, message: '请输入存储桶名称', trigger: 'blur'},
    {max: 50, message: '存储桶名称不能超过50个字符', trigger: 'blur'}
  ],
  storageType: [
    {required: true, message: '请选择存储类型', trigger: 'change'}
  ],
  accessKey: [
    {required: true, message: '请输入访问密钥', trigger: 'blur'}
  ],
  secretKey: [
    {required: true, message: '请输入密钥', trigger: 'blur'}
  ],
  baseUrl: [
    {required: true, message: '请输入访问基础URL', trigger: 'blur'},
    {type: 'url', message: '请输入正确的URL格式', trigger: 'blur'}
  ]
})

// 初始化页面
onMounted(() => {
  getBucketList()
})

// 获取表格数据
const getBucketList = () => {
  reqGetBucketList().then(res => {
  })
}

// 格式化日期时间
const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return ''
  return formatDate(dateTime, 'yyyy-MM-dd HH:mm:ss')
}

// 打开新增弹窗
const openAddDialog = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新增存储桶'
  // 重置表单
  formRef.value?.resetFields()
  bucketForm.id = undefined
  bucketForm.status = '1'
  dialogVisible.value = true
}

// 打开编辑弹窗
const openEditDialog = (row: StorageBucket) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑存储桶'
  // 重置表单并赋值
  formRef.value?.resetFields()
  Object.assign(bucketForm, row)
  dialogVisible.value = true
}

// 处理新增
const handleAdd = async () => {
  // 表单验证
  const valid = await formRef.value?.validate()
  if (!valid) return
  await reqCreateBucket(bucketForm)
  dialogVisible.value = false
  getBucketList()
}

// 处理更新
const handleUpdate = async () => {
  // 表单验证
  const valid = await formRef.value?.validate()
  if (!valid) return
  console.log('更新存储桶：', bucketForm)
  dialogVisible.value = false
  getBucketList()
}

// 处理删除
const handleDelete = (row: StorageBucket) => {
  ElMessageBox.confirm(
      `确定要删除存储桶【${row.bucketName}】吗？`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      } as string
  ).then(() => {
    // 模拟API调用
    console.log('删除存储桶：', row.id)
    // 实际项目中调用接口后刷新表格
    getBucketList()
  })
}

// 处理状态切换
const handleStatusChange = (row: StorageBucket) => {
  const statusText = row.status === 1 ? '启用' : '禁用'
  console.log(`存储桶【${row.bucketName}】${statusText}`)
  // 实际项目中调用接口更新状态
}

// 选择项变化
const handleSelectionChange = (rows: StorageBucket[]) => {
  selectedRows.value = rows
}
</script>

<style scoped>
.operate-bar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px 0;
}
</style>
